import { filter } from 'rxjs/operators';
import { Component, OnInit, Input, ViewChild } from '@angular/core';
import { HttpService } from 'src/app/shared/service/http.service';
import { ModalController, IonInfiniteScroll } from '@ionic/angular';
import { ChooseCityComponent } from '../choose-city/choose-city.component';
import { AppGlobalService } from 'src/app/shared/service/app-global.service';

@Component({
  selector: 'app-all-address-tag',
  templateUrl: './all-address-tag.component.html',
  styleUrls: ['./all-address-tag.component.scss'],
})
export class AllAddressTagComponent implements OnInit {

  @ViewChild(IonInfiniteScroll) infiniteScroll: IonInfiniteScroll;

  @Input() tagData: any;

  listData = []; // 列表数据

  pageNo = 0; // 当前页数

  content = {  // 搜索参数
    pageNo: 1,
    filter: {}
  };

  city: any;

  constructor(
    private http: HttpService,
    private modalController: ModalController,
    private appGlobalService: AppGlobalService,
  ) { }

  ngOnInit() {


    this.listData = this.tagData.data.data;

    this.pageNo = this.tagData.data.pageNo;

    this.city = { name: this.tagData.data.changeModel.title, code: '' };
  }

  loadData(event) {
    setTimeout(() => {
      event.target.complete();

      this.content.pageNo = ++this.pageNo;
      const params = {
        content: this.content,
        id: this.tagData.data.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      let items = [];
      this.http.post("application/submit", params, res => {
        items = res.data.data || [];
        if (items.length <= 0) {
          --this.pageNo;
          // App logic to determine if all data is loaded
          // and disable the infinite scroll
          event.target.disabled = true;
          // this.appGlobalService.showToast('没有数据了...', 1000, 'bottom');
        } else {
          this.listData = [...this.listData, ...items];
        }
      });

    }, 500);
  }


  // 切换城市
  async showCityModel(target) {
    const modal = await this.modalController.create({
      component: ChooseCityComponent,
      componentProps: { value: target, noStorage: true, modalTitle: '选择城市' }  //    首页是1 默认不传或者0
    });
    modal.onDidDismiss().then((data) => {
      const value = data.data;
      if (value.n) {
        this.content.filter[this.tagData.data.changeModel.name] = value.i;
        this.city = { name: value.n, code: value.i };
        const params = {
          content: this.content,
          id: this.tagData.data.submit.id,
          sessionId: localStorage.getItem("sessionId")
        };
        let items = [];
        this.http.post("application/submit", params, res => {
          items = res.data.data || [];
          this.infiniteScroll.disabled = false;
          if (items.length <= 0) {
            this.listData = [];
          } else {
            this.listData = [...items];
          }
        });
      }
    });
    return await modal.present();
  }

}
